/* components */
import { 
  SettingGPTViewHeader,
  SettingGPTViewContent,
  SettingGPTViewDialog
} from "@src/modules/setting/gpt/components";
import SettingGPTManageViewTabs from '@src/modules/setting/gpt/views/manage/tabs'
import SettingGPTManageViewTable from '@src/modules/setting/gpt/views/question/table'
import SettingGPTManageViewOperate from '@src/modules/setting/gpt/views/question/operate'
import SettingGPTQuestionView from '@src/modules/setting/gpt/views/question'
import SettingGPTQuestionViewEdit from '@src/modules/setting/gpt/views/question/edit'
/* enum */
import ComponentNameEnum from "@model/enum/ComponentNameEnum";
/* hooks */
import { 
  useSettingGPTManageList, 
  useSettingListTable,
  useFetchSettingGPTInsertStandardQuestion,
  useFetchSettingGPTUpdateStandardQuestion,
} from "@src/modules/setting/gpt/hooks";
/* model */
import { 
  SettingGPTManageQuestionListFields, 
  SettingGPTQuestionLogListFields 
} from "@src/modules/setting/gpt/model";
/* vue */
import { computed, defineComponent, nextTick } from "vue";
/* scss */
import "@src/modules/setting/gpt/views/manage/index.scss";
/* util */
import platform from "@src/platform";
import { settingListFieldsToColumns } from "@src/modules/setting/gpt/utils";
/* util */
import { getRootWindowInitData } from '@src/util/window'
import { isFalsy } from "@src/util/type";
/* types */
import { SettingGPTQuestionItemType } from "@src/modules/setting/gpt/types";
import Column from "@model/types/Column";
import { message } from "@src/util/message";

type SettingGPTQuestionViewComponent = InstanceType<typeof SettingGPTQuestionView>
type SettingGPTViewDialogComponent = InstanceType<typeof SettingGPTViewDialog>
type SettingGPTQuestionViewEditComponent = InstanceType<typeof SettingGPTQuestionViewEdit>
type SettingGPTManageViewTableComponent = InstanceType<typeof SettingGPTManageViewTable>

enum SettingGPTManageViewEventEnum {
  Input = 'input'
}

export default defineComponent({
  name: ComponentNameEnum.SettingGPTManageView,
  props: {
    
  },
  setup(props, { emit }) {
    
    const {
      loading: _loading,
      dataList,
      page,
      active,
      isQuestionListActive,
      isStandActive,
      isLogActive,
      keyword,
      setActive,
      onKeywordChangeHandler,
      onTabChangeHandler,
      initialize,
      onSetPageNumHandler,
      onSetPageSizeHandler,
      onDeleteQuestionHandler,
      onDeleteBatchQuestionHandler
    } = useSettingGPTManageList()
    
    const { 
      handleSelectionChange, 
      multipleSelection, 
      clearMultipleSelection 
    } = useSettingListTable<SettingGPTQuestionItemType>(emit)
    
    const {
      loading: fetchInsertStandardQuestionLoading,
      fetchInsertStandardQuestion,
      isSuccess: fetchInsertStandardQuestionSuccess
    } = useFetchSettingGPTInsertStandardQuestion()
    
    const {
      loading: fetchUpdateStandardQuestionLoading,
      fetchUpdateStandardQuestion,
      isSuccess: fetchUpdateStandardQuestionSuccess
    } = useFetchSettingGPTUpdateStandardQuestion()
    
    const loading = computed(() => {
      return (
        _loading.value 
        || fetchInsertStandardQuestionLoading.value 
        || fetchUpdateStandardQuestionLoading.value
      )
    })
    
    return {
      loading,
      dataList,
      page,
      active,
      isQuestionListActive,
      isStandActive,
      isLogActive,
      keyword,
      multipleSelection,
      fetchInsertStandardQuestionLoading,
      fetchInsertStandardQuestion,
      fetchInsertStandardQuestionSuccess,
      fetchUpdateStandardQuestionLoading,
      fetchUpdateStandardQuestion,
      fetchUpdateStandardQuestionSuccess,
      handleSelectionChange,
      clearMultipleSelection,
      setActive,
      onKeywordChangeHandler,
      onTabChangeHandler,
      initialize,
      onSetPageNumHandler,
      onSetPageSizeHandler,
      onDeleteQuestionHandler,
      onDeleteBatchQuestionHandler
    }
    
  },
  data() {
    return {
      isFirstLoadQuestionList: true,
      isCreateStandardLib: false,
      currentEditItem: {} as unknown as SettingGPTQuestionItemType
    }
  },
  computed: {
    attrs(): Record<string, any> {
      return {
        directives: [
          {
            name: 'loading',
            value: this.loading
          }
        ]
      }
    },
    columns(): Column[] {
      const fields = this.isLogActive ? SettingGPTQuestionLogListFields : SettingGPTManageQuestionListFields
      return settingListFieldsToColumns(fields)
    },
    title(): string {
      return "应用百科"
    },
    subTitle(): string {
      return '让智能助手为你在群内创建和训练问答机器人；再也不用反复回答相似的业务问题，客服、答疑等场景均可适用。'
    },
    isNotQuestionListActive(): boolean {
      return isFalsy(this.isQuestionListActive)
    },
    loginUser(): Record<string, any> {
      const rootWindowInitData = getRootWindowInitData()
      return rootWindowInitData.user || {}
    },
    loginUserAuth(): Record<string, any> {
      return this.loginUser?.auth || {}
    },
    isShowDelete(): boolean {
      return Boolean(this.loginUserAuth?.XIAOBAO_WIKI_DEL) && this.isStandActive
    },
    isAllowCreate(): boolean {
      return Boolean(this.loginUserAuth?.XIAOBAO_WIKI_EDIT) && this.isStandActive
    },
    isAllowEdit(): boolean {
      return Boolean(this.loginUserAuth?.XIAOBAO_WIKI_EDIT)
    },
    settingGPTQuestionViewComponent(): SettingGPTQuestionViewComponent {
      return this.$refs.SettingGPTQuestionView as SettingGPTQuestionViewComponent
    },
    settingGPTViewDialogComponent(): SettingGPTViewDialogComponent {
      return this.$refs.SettingGPTViewDialog as SettingGPTViewDialogComponent
    },
    settingGPTQuestionViewEditComponent(): SettingGPTQuestionViewEditComponent {
      return this.$refs.SettingGPTQuestionViewEdit as SettingGPTQuestionViewEditComponent
    },
    settingGPTManageViewTableComponent(): SettingGPTManageViewTableComponent {
      return this.$refs.SettingGPTManageViewTable as SettingGPTManageViewTableComponent
    },
    isEditStandardLib(): boolean {
      return isFalsy(this.isCreateStandardLib)
    },
    standardLibDialogTitle(): string {
      return this.isEditStandardLib ? '编辑百科' : '新建百科'
    }
  },
  watch: {
    isQuestionListActive(value) {
      
      if (isFalsy(this.isFirstLoadQuestionList)) {
        return
      }
      
      if (value) {
        this.settingGPTQuestionViewComponent.initialize()
        this.isFirstLoadQuestionList = false
      }
      
    }
  },
  mounted() {
    this.initialize()
  },
  methods: {
    /** 
     * @description 使用说明按钮点击事件
    */
    descriptionButtonClickHandler() {
      platform.openLink('https://doc.shb.ltd/shb_xoqazk/ia4qctp2ly559d1m/eka8tf9wv8x43arx/xgs8aywpqgn7ymug.html')
    },
    /** 
     * @description 渲染使用说明按钮
    */
    renderDescriptionButton() {
      return (
        <el-button
          type="plain-third"
          onClick={this.descriptionButtonClickHandler}
        >
          使用说明
        </el-button>
      )
    },
    onEditQuestionHandler(item: SettingGPTQuestionItemType) {
      
      this.isCreateStandardLib = false
      this.currentEditItem = item
      
      this.settingGPTQuestionViewEditComponent.outsideInitialize(this.currentEditItem as unknown as SettingGPTQuestionItemType)
      this.settingGPTQuestionViewEditComponent.initializeForEdit()
      this.settingGPTViewDialogComponent.open()
      
    },
    onCreateStandLibHandler() {
      
      this.isCreateStandardLib = true
      
      this.currentEditItem = {
        answer: '',
        question: '',
        similarQuestionList: ['']
      } as unknown as SettingGPTQuestionItemType
      
      this.settingGPTQuestionViewEditComponent.outsideInitialize(this.currentEditItem as unknown as SettingGPTQuestionItemType)
      this.settingGPTQuestionViewEditComponent.initializeForCreate()
      this.settingGPTViewDialogComponent.open()
    },
    async onAnswerConfirmHandler() {
      
      const validated = await this.settingGPTQuestionViewEditComponent.validate()
      if (isFalsy(validated)) {
        return
      }
      
      if (this.isCreateStandardLib) {
        return this.onInsertStandardQuestionHandler()
      }
      
      if (this.isEditStandardLib) {
        return this.onUpdateStandardQuestionHandler()
      }
      
      throw new Error('未知的操作')
      
    },
    onInsertStandardQuestionHandler() {
      
      const value = this.settingGPTQuestionViewEditComponent.outsideGetInsideValue()
      
      const params = {
        question: value.question,
        answer: value.answer,
        similarQuestions: value.similarQuestionList
      }
      
      this.fetchInsertStandardQuestion(params).then(() => {
        
        if (isFalsy(this.fetchInsertStandardQuestionSuccess)) {
          return
        }
        
        this.settingGPTViewDialogComponent.close()
        this.initialize()
        
        message.success('新建成功')
        
      })
      
    },
    onUpdateStandardQuestionHandler() {
      
      const value = this.settingGPTQuestionViewEditComponent.outsideGetInsideValue()
      const params = {
        id: this.currentEditItem.id,
        question: value.question,
        answer: value.answer,
        similarQuestions: value.similarQuestionList
      }
      
      this.fetchUpdateStandardQuestion(params).then(() => {
        
        if (isFalsy(this.fetchUpdateStandardQuestionSuccess)) {
          return
        }
        
        this.settingGPTViewDialogComponent.close()
        this.initialize()
        
        message.success('编辑成功')
        
      })
      
    },
    insideOnDeleteBatchQuestionHandler() {
      this.onDeleteBatchQuestionHandler(this.multipleSelection).then(() => {
        nextTick(() => {
          this.clearMultipleSelection()
          this.settingGPTManageViewTableComponent.clearSelection()
          this.settingGPTManageViewTableComponent.rerender()
        })
      })
    }
  },
  render() {
    return (
      <div class={ComponentNameEnum.SettingGPTManageView}>
        
        <SettingGPTViewHeader
          title={this.title}
          subTitle={this.subTitle}
        >
        </SettingGPTViewHeader>
        
        <SettingGPTViewContent>
        
          <SettingGPTManageViewTabs
            value={this.active}
            onInput={this.onTabChangeHandler}
          >
          </SettingGPTManageViewTabs>
          
          <div v-show={this.isNotQuestionListActive}>
            
            <SettingGPTManageViewOperate
              isStandardActive={this.isStandActive}
              isLogActive={this.isLogActive}
              isShowDelete={this.isShowDelete}
              isShowStandardOperate={this.isAllowCreate}
              keyword={this.keyword}
              onCreate={this.onCreateStandLibHandler}
              onChangeKeyword={this.onKeywordChangeHandler}
              onBatchDelete={this.insideOnDeleteBatchQuestionHandler}
            >
            </SettingGPTManageViewOperate>
            
            <SettingGPTManageViewTable
              ref="SettingGPTManageViewTable"
              {...this.attrs}
              columns={this.columns}
              page={this.page}
              value={this.dataList}
              active={this.active}
              isAllowCreate={this.isAllowCreate}
              isAllowEdit={this.isAllowEdit}
              isShowDelete={this.isShowDelete}
              onChangeSelection={this.handleSelectionChange}
              onChangePageNum={this.onSetPageNumHandler}
              onChangePageSize={this.onSetPageSizeHandler}
              onDelete={this.onDeleteQuestionHandler}
              onEdit={this.onEditQuestionHandler}
            >
            </SettingGPTManageViewTable>
            
          </div>
          
          <div v-show={this.isQuestionListActive}>
            <SettingGPTQuestionView
              ref="SettingGPTQuestionView"
            >
            </SettingGPTQuestionView>
          </div>
        
        </SettingGPTViewContent>
        
        <SettingGPTViewDialog
          ref="SettingGPTViewDialog"
          title={this.standardLibDialogTitle}
          disabled={this.loading}
          onConfirm={this.onAnswerConfirmHandler}
        >
          <SettingGPTQuestionViewEdit
            ref="SettingGPTQuestionViewEdit"
            isAdd
            value={this.currentEditItem as unknown as SettingGPTQuestionItemType}
          >
          </SettingGPTQuestionViewEdit>
        </SettingGPTViewDialog>
        
      </div>
    )
  }
})